package com.getpebble.android.core.auth.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.auth.PblSessionManager;
import com.getpebble.android.common.core.trace.Analytics.MobileAppOnboarding;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.framework.fragment.IHandleBackPress;
import com.getpebble.android.common.framework.fragment.PblBaseFragment;
import com.getpebble.android.http.HttpRequestUtil;
import com.getpebble.android.main.activity.MainActivity;
import com.getpebble.android.webview.WebViewUtil;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Response;

public class LoginWebViewFragment extends PblBaseFragment implements IHandleBackPress, FutureCallback<Response<JsonObject>> {
    private static final String TAG = LoginWebViewFragment.class.getSimpleName();
    private String mAccessToken = null;
    private String mEmail = null;
    private ProgressBar mProgressBar;
    private WebView mWebView;

    public class AuthenticationFailureException extends RuntimeException {
        public AuthenticationFailureException(String detailMessage) {
            super(detailMessage);
        }
    }

    private class LoginWebViewClient extends WebViewClient {
        private final Context appContext;

        LoginWebViewClient(Context context) {
            this.appContext = context.getApplicationContext();
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            final String accessToken = findAccessToken(url);
            if (accessToken == null) {
                return super.shouldOverrideUrlLoading(view, url);
            }
            HttpRequestUtil.fetchMeData(this.appContext, true, accessToken, new FutureCallback<Response<JsonObject>>() {
                public void onCompleted(Exception e, Response<JsonObject> responseString) {
                    int responseCode = 0;
                    if (!(responseString == null || responseString.getHeaders() == null)) {
                        responseCode = responseString.getHeaders().getResponseCode();
                    }
                    if (e == null && responseCode == 200) {
                        JsonObject result = (JsonObject) responseString.getResult();
                        if (result == null) {
                            Toast.makeText(LoginWebViewClient.this.appContext, LoginWebViewFragment.this.getString(R.string.onboarding_login_failed_message), 1).show();
                            Trace.error("LoginWebViewClient", "onCompleted: result was null");
                            return;
                        }
                        LoginWebViewFragment.this.mEmail = result.get("email").getAsString();
                        HttpRequestUtil.fetchMeData(LoginWebViewClient.this.appContext, false, accessToken, LoginWebViewFragment.this, 8000);
                        return;
                    }
                    Trace.error("LoginWebViewClient", "Failed to get email: " + responseCode, e);
                    LoginWebViewFragment.this.showAccountInfoFailure();
                }
            }, 8000);
            LoginWebViewFragment.this.mAccessToken = accessToken;
            return true;
        }

        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            LoginWebViewFragment.this.mProgressBar.setVisibility(8);
        }

        private String findAccessToken(String url) {
            String accessToken = null;
            if (url.startsWith("pebble://login#")) {
                for (String queryArg : url.replaceFirst("pebble://login#", "").split("&")) {
                    if (queryArg.startsWith("access_token")) {
                        accessToken = queryArg.split("=")[1];
                    }
                }
                if (accessToken == null) {
                    MobileAppOnboarding.logOnboardingLoginFailedEvent();
                    throw new AuthenticationFailureException("Found redirect URI without access_token");
                }
            }
            return accessToken;
        }
    }

    public int getLayoutId() {
        return R.layout.fragment_webview;
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.mWebView = (WebView) container.findViewById(R.id.webView);
        this.mWebView.getSettings().setDomStorageEnabled(true);
        this.mProgressBar = (ProgressBar) container.findViewById(R.id.progressbar);
        String url = null;
        if (getArguments() != null) {
            url = getArguments().getString("login_web_view_url");
        }
        if (url == null) {
            throw new IllegalArgumentException("Missing required URL argument.");
        }
        loadWebView(url);
    }

    @SuppressLint({"SetJavaScriptEnabled"})
    private void loadWebView(String url) {
        CookieManager.getInstance().removeAllCookie();
        WebSettings webSettings = this.mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(2);
        this.mWebView.setWebViewClient(new LoginWebViewClient(getActivity().getApplicationContext()));
        this.mWebView.setLayerType(1, null);
        WebViewUtil.appendPebbleUserAgentStringToWebview(this.mWebView);
        this.mWebView.setBackgroundColor(getResources().getColor(R.color.black));
        this.mWebView.loadUrl(url);
    }

    private void showAccountInfoFailure() {
        Activity activity = getActivity();
        if (activity != null) {
            MobileAppOnboarding.logOnboardingLoginFailedEvent();
            Toast.makeText(activity, R.string.app_failed_get_account_info, 1).show();
        }
    }

    public void onCompleted(Exception e, Response<JsonObject> responseString) {
        if (e != null) {
            Trace.error(TAG, "Error getting account info", e);
            showAccountInfoFailure();
            return;
        }
        JsonObject user = PblSessionManager.getUserFromResponse(responseString);
        Activity activity;
        if (user == null) {
            activity = getActivity();
            if (activity != null) {
                Toast.makeText(activity, getString(R.string.onboarding_login_failed_message), 1).show();
            }
            Trace.error(TAG, "Failed to login: user was null.");
            return;
        }
        MobileAppOnboarding.logOnboardingLoginSucceeded(this.mAccessToken);
        PebbleApplication.getSessionManager().createAccount(this.mEmail, "mockpass", this.mAccessToken, user.get("id").getAsString(), user.get("uid").getAsString());
        PebbleApplication.getSyncManager().setPeriodicSync();
        PebbleApplication.getSyncManager().syncAll();
        activity = getActivity();
        if (activity != null) {
            Intent intent = new Intent(activity, MainActivity.class);
            intent.addFlags(268500992);
            activity.startActivity(intent);
            activity.finish();
        }
    }

    public boolean canGoBack() {
        return this.mWebView != null && this.mWebView.canGoBack();
    }

    public void goBack() {
        if (this.mWebView != null) {
            this.mWebView.goBack();
        }
    }
}
